package celiasoft.itasalib.query.resultparser;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.query.resultparser.W3CParsingHandler.ElementParser;
import celiasoft.itasalib.structures.DataElement;
import celiasoft.itasalib.structures.EpisodeData;
import celiasoft.itasalib.structures.News;

public class QueryAllNewsResultParser extends IQueryResultParser {

	@SuppressWarnings("unused")
	private static final String TAG = "itasalib.parser.QueryAllNewsResultPaser";

	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {
		
		ArrayList<DataElement> res = new ArrayList<DataElement>();

		NodeList news =  doc.getElementsByTagName("news"); // attention: multiple news node possible
		
		if(news.getLength() < 1 
				|| !news.item(0).hasChildNodes()){
			return res;
		}
		
		NodeList nodes = news.item(0).getChildNodes();
		
		if(nodes.getLength() > 0){
			for(int i = 0; i < nodes.getLength(); i++){
				Node n = nodes.item(i);
				
				DataElement el = parseNode(n);
				if(el != null){
					res.add(el);
				}
			}
		}
		
		if(res.size() > 0){
			setMetaData(doc, meta);
		}
		
		return res;
	}


	private DataElement parseNode(Node n) {
		
		Element e = (Element)n;
		
		
		int id = -1;
		id = W3CParsingHandler.parseIntValue(e, "id");
		if(id == -1)
			return null;
		
		News el = new News(id);
		
		el.setShowId(W3CParsingHandler.parseIntValue(e, "show_id"));
		el.setName(DomHandler.getValue(e, "show_name"));
		//el.setSpecial(DomHandler.getValue(e, "special")); //ignore
		el.setCategory(W3CParsingHandler.parseIntValue(e, "category"));
		
		el.setImage(W3CParsingHandler.parseURLValue(e, "image"));
		el.setImageBy(DomHandler.getValue(e, "image_by"));
		
		el.setTeam(DomHandler.getValue(e, "team"));
		el.setSubmitDate(W3CParsingHandler.parseW3CDateValue(e, "submit_date"));
		el.setSubmittedBy(DomHandler.getValue(e, "submitted_by"));
		
		el.setThumb(W3CParsingHandler.parseURLValue(e, "thumb"));
		
		el.setEpisodes(W3CParsingHandler.parseList(e, "episodes", new ElementParser<EpisodeData>(){

			public EpisodeData parseElement(Node n) {
				Element e = (Element)n;
				
				String episode = DomHandler.getValue(e, "episode");
				
				EpisodeData el = null;
				try {
					el = EpisodeData.parse(episode);
				} catch (MalformedEpisodeDataException e1) {
					e1.printStackTrace();
				}
				
				return el;
			}
			
		}));
		
		
		return el;
	}


	
}
